package com.hightrast.service.util;


import com.hightrast.service.api.interfaceFuc.TreeNode;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class TreeUtils {

    /**
     * 构建树形结构
     * @param items 所有节点的列表
     * @param getId 获取节点 ID 的函数
     * @param getParentId 获取节点 Parent ID 的函数
     * @param setChildren 设置子节点的函数
     * @return 树形结构的根节点列表
     */
    public static <T extends TreeNode<T>> List<T> buildTree(
            List<T> items,
            Function<T, Long> getId,
            Function<T, Long> getParentId,
            Function<T, List<T>> getChildren,
            Function<T, Void> setChildren)
    {
        
        // 按 parentId 分组
        Map<Long, List<T>> groupedByParentId = items.stream()
                .collect(Collectors.groupingBy(item -> getParentId.apply(item) == null ? 0L : getParentId.apply(item)));

        // 为每个节点设置子节点
        items.forEach(item -> {
            List<T> children = groupedByParentId.get(getId.apply(item));
            if (children != null && !children.isEmpty()) {
                setChildren.apply(item);
            }
        });

        // 返回根节点
        return groupedByParentId.getOrDefault(0L, Collections.emptyList());
    }
    public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }

}